package com.alstudio.utils.mission;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.util.ArrayList;

import com.alstudio.app.ALLocalEnv;
import com.alstudio.utils.android.net.AndroidNetUtils;
import com.alstudio.utils.log.ALLog;
import com.alstudio.utils.mission.parser.XmlNameSpaceParser;
import com.alstudio.utils.mission.parser.XmlNameSpaceParser.CheckNameSpaceCallback;

public class ALMissionHttpManager {

	private MissionInfoCallback mCallback = null;
	private MissionParserConfig mConfig;

	public void setMissionCallback(MissionInfoCallback callback) {
		mCallback = callback;
	}

	public ALMissionHttpManager() {
		// TODO Auto-generated constructor stub
		mConfig = new MissionParserConfig();
	}

	public ALMissionHttpManager(MissionInfoCallback callback) {
		// TODO Auto-generated constructor stub
		this();
		mCallback = callback;
	}

	public void checkTaskList(final String url) {
		new Thread() {
			public void run() {
				HttpURLConnection conn = null;
				BufferedReader reader = null;
				ALLog.d( "任务请求连接为 " + url);
				try {
					conn = AndroidNetUtils
							.buildHttpUrlConnectionUsingGetMethod(url,
									ALLocalEnv.getLocalEnv().getDefaultWebHeads());
					reader = new BufferedReader(new InputStreamReader(
							conn.getInputStream()));

					String line;
					String s = "";

					while ((line = reader.readLine()) != null) {
						// System.out.println(line);
						s += line;
					}
					ALLog.d( s);
					conn.disconnect();
					reader.close();
					startParse(s);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					if (mCallback != null) {
						ALLog.d( "连接出现异常");
						mCallback.onConnectFail();
					}
				} finally {
					try {
						conn.disconnect();
						reader.close();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			};
		}.start();
	}

	private void startParse(final String data) {
		XmlNameSpaceParser ns = new XmlNameSpaceParser(
				new CheckNameSpaceCallback() {

					@Override
					public void onGetNameSpace(String ns) {
						// TODO Auto-generated method stub
						ALLog.d( "得到命名空间是 " + ns);
						mConfig.getXmlParser(data, ns, mCallback);
					}
				});
		try {
			ns.parseXmlPackage(data, null);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public interface MissionInfoCallback {
		public void onGetTaskList(ArrayList<MissionInfo> tasks, int code,int dailyComplete);


		public void onConnectFail();
	}

}
